import json

from django.http import JsonResponse
from django.shortcuts import render, HttpResponse
from django.views import View

from django_redis import get_redis_connection

from libs.captcha.captcha import captcha
from libs.yuntongxun.sms import CCP
from celery_tasks.sms.tasks import celery_send_sms_code

from random import randint


# Create your views here.

class ImageCodeView(View):

    def get(self, request, uuid):
        # 内容 , 二进制
        text, image = captcha.generate_captcha()

        # 建立redis连接
        redis_cli = get_redis_connection('code')
        # name time value
        redis_cli.setex(uuid, 100, text)

        # content_type->响应体数据类型  大类/小类 image/jpeg image/png image/gif
        return HttpResponse(image, content_type='image/jpeg')


class SmsCodeView(View):

    def get(self, request, mobile):

        image_code = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')

        if not all([image_code, uuid]):
            return JsonResponse({"code": 400, "errmsg": "参数不全"})

        redis_cli = get_redis_connection('code')
        redis_image_code = redis_cli.get(uuid)

        if redis_image_code is None:
            return JsonResponse({"code": 400, "errmsg": "验证码过期"})

        if redis_image_code.decode().lower() != image_code.lower():
            return JsonResponse({"code": 400, "errmsg": "验证码错误"})

        # 查询标记
        send_flag = redis_cli.get("send_flag_%s" % mobile)
        if send_flag is not None:
            return JsonResponse({"code": 400, "errmsg": "频繁发送"})

        sms_code = "%06d" % randint(0, 999999)

        pipeline = redis_cli.pipeline()
        pipeline.setex(mobile, 300, sms_code)
        # 添加标记 检测60s内是否重复请求
        pipeline.setex("send_flag_%s" % mobile, 60, 1)
        pipeline.execute()

        # CCP.send_template_sms(mobile, [sms_code, 5], 1)
        celery_send_sms_code.delay(mobile, sms_code)
        return JsonResponse({"code": 0, "errmsg": "完成"})
